package cn.edu.gdut.deepcode.component;


import cn.edu.gdut.deepcode.config.MinIOProperties;
import io.minio.*;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import static cn.edu.gdut.deepcode.constant.GlobalConstant.FILE_CONTENT_TYPE;
import static cn.edu.gdut.deepcode.constant.GlobalConstant.MINIO_DOWNLOAD_EXPIRY_MINUTES;


//@Component
@RequiredArgsConstructor
@Slf4j
public class MinIOService{

    private final MinioClient minioClient;

    private final MinIOProperties properties;

  // -------------------- 基础文件操作 --------------------
    public String upload(InputStream stream,long size,long partSize,String objectName) {
        try (InputStream inputStream = stream) {
            ensureBucketExists();
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(properties.getBucketName())
                            .object(objectName)
                            .stream(inputStream, size, partSize)
                            .contentType(FILE_CONTENT_TYPE)
                            .build());
            return objectName;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    public InputStream download(String objectName) throws Exception {
        return minioClient.getObject(
                        GetObjectArgs.builder()
                                .bucket(properties.getBucketName())
                                .object(objectName)
                                .build());
    }


    // ------------------- 生成预签名下载URL -------------------
    public String  presignedDownloadUrl(String objectName) throws Exception {
        Integer expiryMinutes = properties.getDownloadExpiryMinutes();
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(properties.getBucketName())
                .object(objectName)
                .expiry(expiryMinutes !=null
                                ?expiryMinutes
                                : MINIO_DOWNLOAD_EXPIRY_MINUTES
                        , TimeUnit.MINUTES)
                .build());
    }

    private void ensureBucketExists() {
        try {
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(properties.getBucketName()).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(properties.getBucketName()).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("存储桶操作失败: " + e.getMessage());
        }
    }


}
